package com.yupi.yupicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Deprecated
@Slf4j
@Service
@RequiredArgsConstructor
public class FileManager {


    private final CosManager cosManager;
    private final CosClientConfig cosClientConfig;
    private final ApplicationEventPublisher applicationEventPublisher;


    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix){
        //校验图片
        validPicture(multipartFile);
        //图片上传地址
        String uuid= RandomUtil.randomString(16);
        String originFilename=multipartFile.getOriginalFilename();
        String uploadFilename=String.format("%s_%s.%s", DateUtil.formatDate(new Date()),  uuid, FileUtil.getSuffix(originFilename));
        String uploadPath=String.format("/%s/%s",uploadPathPrefix,uploadFilename);
        //创建临时文件
        File file=null;
        try {
            file=File.createTempFile(uploadPath,null);
            multipartFile.transferTo(file);
            //上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth=imageInfo.getWidth();
            int picHeight=imageInfo.getHeight();
            double picScale= NumberUtil.round(picWidth*1.0/picHeight,2).doubleValue();
            //封装返回结果
            UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                    .picName(FileUtil.mainName(originFilename))
                    .picWidth(picWidth)
                    .picHeight(picHeight)
                    .picScale(picScale)
                    .picFormat(imageInfo.getFormat())
                    .picSize(FileUtil.size(file))
                    .url(cosClientConfig.getHost() + "/" + uploadPath)
                    .build();
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            this.deleteTempFile(file);
        }

    }
    public UploadPictureResult uploadPictureByUrl(String fileUrl ,String uploadPathPrefix){
        //校验图片
        validPicture(fileUrl);
        //图片上传地址
        String uuid= RandomUtil.randomString(16);
        String originFilename=FileUtil.mainName(fileUrl);
        String uploadFilename=String.format("%s_%s.%s", DateUtil.formatDate(new Date()),  uuid,
                FileUtil.getSuffix(originFilename));
        String uploadPath=String.format("/%s/%s",uploadPathPrefix,uploadFilename);

        File file=null;

            try {
                file=File.createTempFile(uploadPath,null);
                HttpUtil.downloadFile(fileUrl,file);
                //上传
                PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
                ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
                int picWidth=imageInfo.getWidth();
                int picHeight=imageInfo.getHeight();
                double picScale= NumberUtil.round(picWidth*1.0/picHeight,2).doubleValue();
                UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                        .picName(FileUtil.mainName(originFilename))
                        .picWidth(picWidth)
                        .picHeight(picHeight)
                        .picScale(picScale)
                        .picFormat(imageInfo.getFormat())
                        .picSize(FileUtil.size(file))
                        .url(cosClientConfig.getHost() + "/" + uploadPath)
                        .build();
                return uploadPictureResult;
            } catch (IOException e) {
                log.error("图片上传到对象存储失败", e);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
            }finally {
                this.deleteTempFile(file);
            }


    }



    //校验图片
    public  void  validPicture(MultipartFile multipartFile){
        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCode.PARAMS_ERROR,"文件不能为空");
        //校验文件大小
        long filesize=multipartFile.getSize();
        final long ONE_M=1024*1024;
        ThrowUtils.throwIf(filesize>2*ONE_M, ErrorCode.PARAMS_ERROR,"文件大小不能超过2M");
        //校验文件后缀
        String fileSuffix= FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_FORMAT_LIST= Arrays.asList("jpg","jpeg","png","gif","webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR,"文件格式错误");
    }

    //校验Url
    public  void  validPicture(String fileUrl){
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"文件不能为空");
        //验证URL格式
        try {
            new URL(fileUrl);// 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        //验证URL协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://")&&!fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");
        //发送HEAD请求验证文件是否存在
        HttpResponse response=null;
        try{
            HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if(response.getStatus()!= HttpStatus.HTTP_OK){
                return;
            }
            //校验文件类型
            String contentType = response.header("Content-Type");
            if(StrUtil.isNotBlank(contentType)){
                //允许图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),  ErrorCode.PARAMS_ERROR, "文件类型错误");

            }
            //校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if(StrUtil.isNotBlank(contentLengthStr)){
                long contentLength = Long.parseLong(contentLengthStr);
                final long TWO_MB=  1024*1024*2L;
                ThrowUtils.throwIf(contentLength>TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");

            }
        }finally {
            if(response!=null){
                response.close();
            }
        }


    }

    //删除临时文件

    public void deleteTempFile(File file){
        if(file!=null){
            return;
        }
        //删除
        boolean delete = file.delete();
        if(!delete){
            log.error("file delete error,file={}",file.getAbsolutePath());
        }
    }

}
